package cn.ltgodm.template.user.service.impl;

import cn.ltgodm.template.common.constant.CacheConstants;
import cn.ltgodm.template.common.constant.Constants;
import cn.ltgodm.template.common.constant.UserConstants;
import cn.ltgodm.template.common.domain.entity.LoginUser;
import cn.ltgodm.template.common.domain.entity.User;
import cn.ltgodm.template.common.exception.ServiceException;
import cn.ltgodm.template.common.exception.user.CaptchaException;
import cn.ltgodm.template.common.exception.user.UserNotExistsException;
import cn.ltgodm.template.common.exception.user.UserPasswordNotMatchException;
import cn.ltgodm.template.common.utils.*;
import cn.ltgodm.template.common.content.AuthenticationContextHolder;
import cn.ltgodm.template.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author ltgodm
 * @date 2024-03-19 08:36:51
 * 登录业务逻辑
 */
@Component
@Slf4j
public class LoginService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserService userService;
    @Resource
    private AuthenticationManager authenticationManager;

    @Value("${user.captcha.enable}")
    private boolean captchaEnable;

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     验证码唯一标识
     * @return 返回token
     */
    public String login(String username, String password, String code, String uuid) {
        //校验验证码
        validateCaptcha(username, code, uuid);

        //登录前置校验
        loginPreCheck(username, password);

        //用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                userService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"));
                throw new UserPasswordNotMatchException();
            } else {
                userService.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage());
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        //记录登录操作日志
        userService.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //记录登录用户信息
        recordLoginInfo(loginUser.getUserId());
        //生成token并返回
        return tokenService.createToken(loginUser);
    }


    /**
     * 记录用户登录信息
     * @param userId 用户id
     */
    private void recordLoginInfo(Long userId) {
        User user = new User();
        user.setUserId(userId);
        user.setLoginIp(IpUtils.getIpAddr());
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateById(user);
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 密码
     */
    private void loginPreCheck(String username, String password) {
        //用户名密码为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            userService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null"));
            throw new UserNotExistsException();
        }
        //账号不在指定范围
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            userService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"));
            throw new UserPasswordNotMatchException();
        }
        //密码不在指定范围
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            userService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"));
            throw new UserPasswordNotMatchException();
        }
        //todo ip黑名单校验

    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     验证码唯一标识
     */
    private void validateCaptcha(String username, String code, String uuid) {
        //验证码是否开启
        if (captchaEnable) {
            String verify = CacheConstants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisCache.getCacheObject(verify);
            redisCache.deleteObject(verify);
            if (StringUtils.isEmpty(captcha)) {
                //验证码已过期
                userService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
                throw new CaptchaException();
            } else if (!code.equalsIgnoreCase(captcha)) {
                //验证码不正确
                userService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
                throw new CaptchaException();
            }
        }
    }





}
